export default {
  data() {
    return {
      tableIndex: null,
      tableScope: null,
      isTableGetEnd: false,
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            let end = new Date()
            let start = new Date()
            start = start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
            end = end.getTime() - ((end.getSeconds() * 1000) + (end.getMinutes() * 60 * 1000) + (end.getHours() * 3600 * 1000))
            // console.log(start, end)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            let end = new Date()
            let start = new Date()
            start = start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
            end = end.getTime() - ((end.getSeconds() * 1000) + (end.getMinutes() * 60 * 1000) + (end.getHours() * 3600 * 1000))
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            let end = new Date()
            let start = new Date()
            start = start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
            end = end.getTime() - ((end.getSeconds() * 1000) + (end.getMinutes() * 60 * 1000) + (end.getHours() * 3600 * 1000))
            picker.$emit('pick', [start, end])
          }
        }]
      },
      sourceImg: {
        '2': require('@/assets/dashboard/dashbpard_sapp.png'),
        '3': require('@/assets/dashboard/dashbpard_h5.png'),
        '4': require('@/assets/dashboard/dashbpard_wechat.png'),
        '7': require('@/assets/dashboard/dashbpard_alipay.png'),
        '8': require('@/assets/dashboard/dashbpard_baidu.png'),
        '9': require('@/assets/dashboard/dashbpard_toutiao.png'),
        '--': '--'
      },
      sourceType: {
        '1': '导入',
        '2': '微信小程序',
        '3': 'H5',
        '4': '公众号',
        '5': '安卓',
        '6': '苹果',
        '7': '支付宝小程序',
        '8': '百度小程序',
        '9': '头条小程序',
        '--': '--'
      },
      tableFormatData: {},
      getRowKeys(row, key) {
        return row[`${key}`]
      }
    }
  },
  props: {},
  created() {
    this.$nextTick(() => {
      if (this.$route.query) {
        Object.assign(this['tableFormatData'][`${this.$currentTable}`]['files'], this.$route.query)
      }
      this.copyFilesEmpty()
      this.getTableList()
    })
  },
  filters: {
    address(scope) {
      return `${scope.province['value']}-${scope.city['value']}-${scope.area['value']}`
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return require('@/utils').parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    }
  },
  computed: {
    $currentTable() {
      return this['tableFormatData'][`${'current'}`]
    },
    $tableIndex() {
      return this.tableIndex || -1
    },
    // 表格数据
    $tableData() {
      return this['tableFormatData'][`${this.$currentTable}`]['tableData']
    },
    // 表格的分页数据
    $pagination() {
      return this['tableFormatData'][`${this.$currentTable}`]['pagination']
    },
    // 表格的api
    $tableApiConfig() {
      return this['tableFormatData'][`${this.$currentTable}`]['api']
    },
    $tableScope() {
      return this.tableScope || {}
    },
    isTableFormatDataArray() {
      return Array.isArray(this.$tableData) && this.$tableData['length'] > 0
    },
    hasTableData() {
      return this.isTableFormatDataArray ? (this.$tableData || this.tableData.length > 0) : (this[`${this.$tableData['redirect']}`] || false)
    },
    isTableFormatGetEnd() {
      return this.isTableGetEnd
    },
    isGroup() {
      return !(
        this['tableFormatData'][`${this.$currentTable}`]['files'][this.rowId]
          .length > 0
      )
    },
    rowId() {
      return this['tableFormatData'][`${this.$currentTable}`]['rowId'] ? this['tableFormatData'][`${this.$currentTable}`]['rowId'] : 'ids'
    }
  },
  component: {},
  methods: {
    getFilters() {
      const { page, list_rows } = this.$pagination
      const files = this['tableFormatData'][`${this.$currentTable}`]['files'] || {}
      files[this.rowId] = this.filtersIds(files[this.rowId] || [], files['redirect'])
      if (this.config && this.config.model === 'normal' && this.config.goods_type === 'all') {
        files.goods_type = 'all'
      }
      return Object.assign(files, { page, list_rows })
    },
    filtersIds(array = [], key = 'id') {
      if (array.length > 0) {
        const result = []
        array.map(item => result.push(item[key] || ''))
        return result
      }
      return array
    },
    copyFilesEmpty() {
      Object.keys(this['tableFormatData']).map((item) => {
        if (!['current'].includes(item)) {
          const filesEmpty = require('@/filters/index').assignCopy(this['tableFormatData'][`${item}`]['files'])
          this['tableFormatData'][`${item}`]['filesEmpty'] = filesEmpty
        }
      })
    },
    // 获取列表数据
    getTableList(params = {}) {
      if (this.$tableApiConfig && !this.$tableApiConfig['noCreate']) {
        this.isTableGetEnd = false

        this.getRequest('getList')(this.getFilters()).then(response => {
          const { data: { data: tableData = {} } = {} } = response
          if (tableData) {
            /**
             * Notes:获取列表外面的其他值（定义otherData对象属性，在对象里面定义自己需要获取的额外属性）
             * User: mlq
             */
            for (const key in tableData) {
              if (
                key != 'data' &&
                key != 'current_page' &&
                key != 'last_page' &&
                key !=
                'total' &&
                key != 'per_page' &&
                tableData.hasOwnProperty(key) &&
                this.tableFormatData[this.tableFormatData.current].otherData
              ) {
                this.tableFormatData[this.tableFormatData.current].otherData[key] = tableData[key]
              }
            }
          }

          this.$nextTick(() => {
            if (!Object.is(tableData, null)) {
              const tableFormatData = this['tableFormatData'][`${this.$currentTable}`]
              // console.log('_________________________________',tableFormatData)
              const { noPages } = tableFormatData

              // //console.log('总数据',pagination.is_syn)
              if (!noPages) {
                tableFormatData['tableData'] = tableData.data || []
                this.$pagination['total'] = tableData.total || this.$pagination['total']
              } else {
                tableFormatData['tableData'] = tableData || []
                this.$pagination['total'] = (tableData.length === 0 ? 0 : tableData.length) || this.$pagination['total']
              }
              tableFormatData['files']['checkall'] = '0'
            }
            // 判断用户列表是否在加载
            if (response.data.data.is_syn === true) {
              this.AcquisitionProgress()
            }
            this.isTableGetEnd = true
            this.changeTableCallBack && this.changeTableCallBack({ event: 'getList', params: { response, tableData, argument: params } })
          })
        })
      }
    },
    delTableItem(id) {
      const filters = this.getFilters()
      filters[this.rowId] = [id]
      this.delTableList('filters', filters)
    },
    // 删除表格数据
    delTableList(filters, data) {
      const { type, msg } = this.getMsgConfig('del')
      this.$confirm(msg, '注意', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: type
      }).then(() => {
        this.getRequest('delList')((filters === 'filters') ? data : this.getFilters()).then(response => {
          const { code, message } = response.data
          this.$message({
            message: message || (code === 0 ? '操作失败' : '操作成功'),
            type: (code === 0) ? 'error' : 'success'
          })
          if (code === 1) {
            this['tableFormatData'][`${this.$currentTable}`]['files'][this.rowId] = []
            this.getTableList()
            this.changeTableCallBack && this.changeTableCallBack({ event: 'del', params: { filters, data } })
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    changeTableParmas(params, site, warning,outher = {}) {
      const { isWarning = false, warning: msg, cancel = '已取消操作', router = {} } = warning
      if (!isWarning) {
        this.changeTableRequest(site, params, router, warning,outher)
      } else {
        this.$confirm(msg, '注意', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.changeTableRequest(site, params, router, warning,outher)
        }).catch(() => {
          if (typeof cancel === 'string') {
            this.$message({
              type: 'info',
              message: cancel
            })
          } else {
            const { msg = '已取消操作', val } = cancel
            if (!!val.scope && !!val.cancelStatus) {
              val.scope.row[`${val.cancelStatus.key}`] = val.cancelStatus.val
              this.$message({
                type: 'info',
                message: msg
              }) 
            }
          }
        })
      }
    },
    changeTableRequest(site, params, { type = '', path = '', code = '' }, warning = {},outher = {}) {
      const { isGroup = false } = params
      const { cancel = '已取消操作' } = warning
      if (isGroup) {
        const filters = this.getFilters()
        params[this.rowId] = filters[this.rowId]
      }

      //加载效果
      if(typeof outher.loading !== 'undefined'){
          outher.loading = !outher.loading;
      }

      site.api(params).then(response => {
        const { code, message } = response.data
        this.$message({
          message: message || (code === 0 ? `操作失败` : `操作成功`),
          type: (code === 0) ? 'error' : 'success'
        })
        if (code === 1) {
          if (type && path) {
            this.$router[type](path)
          } else {
            this.getTableList()
            this.changeTableCallBack && this.changeTableCallBack({ event: 'change', params: { response, site, params } })
          }
        }
      }).catch(() => {
        if (typeof cancel !== 'string') {
          const { val } = cancel
          if (!!val.scope && !!val.cancelStatus) {
            val.scope.row[`${val.cancelStatus.key}`] = val.cancelStatus.error
          }
        }
      }).finally(() => {
        //加载效果
          if(typeof outher.loading !== 'undefined'){
            outher.loading = !outher.loading;
        }
      })

    },
    changeTableItem(params, site, warning = {},outher = {}) {
      console.log('------------------------------------',params, site, warning, 'changeTableItem')
      this.changeTableParmas(params, site, warning,outher)
    },
    changeTableItemToggle(row, params, site, warning = {}) {
      if (row) {
        this.clearSelection()
        params.isGroup = true
        this.$refs[`${this.$currentTable}`].toggleRowSelection(row)
        this.changeTableParmas(params, site, warning)
      }
    },
    sortTableFormat(params) {
      this.$refs[`${this.$currentTable}`].sort(params)
    },
    getRequest(request) {
      return this.$tableApiConfig[request]
    },
    getMsgConfig(request) {
      const msgConfig = this.$tableApiConfig['msgConfig']

      if (msgConfig) {
        return msgConfig[request]
      }
      return {
        type: 'warning',
        msg: '确定删除选择的数据项?'
      }
    },
    getOtherData(request) {

    },
    filesEmpty() {
      console.log(this['tableFormatData'][`${this.$currentTable}`]['filesEmpty'])
      const [filesEmpty] = require('@/filters/index').assignCopy(...this['tableFormatData'][`${this.$currentTable}`]['filesEmpty'])
      this.$set(this['tableFormatData'][`${this.$currentTable}`], 'files', filesEmpty)
      this.clearSelection()
      this.filesSerch()
    },
    filesSerch() {
      // 搜索从第一页开始
      this.$set(this.$pagination, 'page', 1)
      this.getTableList()
    },
    listPageChange() {
      this.clearSelection()
      if (this.hasTableData) {
        this.$nextTick(() => {
          this.getTableList()
        })
      }
    },
    // 全选的状态切换
    toggleSelection(change) {
      //  1 选中
      //  0 未选中
      if (this.$currentTable && change === '1') {
        this.clearSelection()
        if (this.isTableFormatDataArray) {
          this.$tableData.forEach(
            row => {
              let falg = true
              if (this.disabelsRow && this.disabelsRow.length && this.disabelsRow.indexOf(row) > -1) {
                falg = false
              }
              falg && this.$refs[`${this.$currentTable}`].toggleRowSelection(row)
            }
          )
        }
      } else {
        this.clearSelection()
      }
    },
    toggleAllSelection() {
      const hasRef = this.$refs[`${this.$currentTable}`]
      hasRef && hasRef['toggleAllSelection']()
    },
    // 清除选中
    clearSelection() {
      if (this.$refs[`${this.$currentTable}`]) {
        if (Array.isArray(this.$refs[`${this.$currentTable}`])) {
          this.$refs[`${this.$currentTable}`].map(item => {
            item.clearSelection()
          })
        } else {
          this.$refs[`${this.$currentTable}`].clearSelection()
        }
      }
    },
    handleSelectionChange(val) {
      this['tableFormatData'][`${this.$currentTable}`]['files'][this.rowId] = val
      // console.log(this['tableFormatData'][`${this.$currentTable}`]['files']['ids'])
    },
    getSelectionIdsKeys(keyName) {
      const keys = this['tableFormatData'][`${this.$currentTable}`]['files'][this.rowId]
      const result = []
      if (Array.isArray(keys) && keys.length > 0) {
        keys.map(item => {
          result.push(item[`${keyName}`])
        })
      }
      return result
    }
  }
}
